package com.zzxx.wechat.controller;

import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ceshi {
    public static void main(String[] args) throws IOException {
        // 设置ChromeDriver的路径
       // System.setProperty("webdriver.chrome.driver", "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe");
        // System.setProperty("webdriver.chrome.driver", "D:\\software\\chromedriver\\chromedriver-win64\\chromedriver.exe");
        System.setProperty("webdriver.chrome.driver", "/Users/zzxx/software/chromedriver/chromedriver-mac-arm64/chromedriver");


        // 设置代理服务器信息
        String proxyHost = "brd.superproxy.io";
        int proxyPort = 33335;
        String proxyUser = "brd-customer-hl_b3246fe5-zone-residential_proxy1-country-jp";
        String proxyPassword = "n62p45lthsqb";
        // 创建带认证的代理扩展
        String proxyZipPath = createProxyAuthExtension(proxyHost, proxyPort, proxyUser, proxyPassword);
        // 创建代理对象
        // 创建代理对象 - 正确格式为 host:port
        Proxy proxy = new Proxy();
        String proxyString = proxyHost + ":" + proxyPort;
        proxy.setHttpProxy(proxyString);
        proxy.setSslProxy(proxyString);
        proxy.setProxyType(Proxy.ProxyType.MANUAL);

        ChromeOptions options = new ChromeOptions();

        // 添加代理设置到ChromeOptions
        options.setCapability("proxy", proxy);
        // 添加代理认证扩展
        options.addExtensions(new File(proxyZipPath));
        // 使用代理认证扩展方式
        // 构建代理认证字符串
     //   String proxyAuthString = "--proxy-server=http://" + proxyString;
   //     options.addArguments(proxyAuthString);
     options.addArguments("ignore-certificate-errors");
        options.addArguments("--ignore-ssl-errors=yes")  ;


        // 禁用自动化提示
        options.addArguments("--disable-blink-features=AutomationControlled");
        options.addArguments("--no-sandbox");
        options.addArguments("--disable-dev-shm-usage");


        //   proxy.setHttpProxy("brd-customer-hl_b3246fe5-zone-residential_proxy1-country-jp:n62p45lthsqb@brd.superproxy.io:33335"); // 设置HTTP代理
      //  proxy.setSslProxy("brd-customer-hl_b3246fe5-zone-residential_proxy1-country-jp:n62p45lthsqb@brd.superproxy.io:33335"); // 设置HTTPS代理



        //    options.addArguments("---headless");

        //options.setCapability(CapabilityType.PROXY, proxy);
  //  options.addArguments("--proxy-server=brd.superproxy.io:33335");
   /// options.addArguments("--proxy-auth=brd-customer-hl_b3246fe5-zone-residential_proxy1-country-jp:n62p45lthsqb");

//        options.addArguments("--proxy-server=brd.superproxy.io:33335");
//        options.addArguments("--proxy-username=brd-customer-hl_b3246fe5-zone-residential_proxy1-country-jp");
//        options.addArguments("--proxy-password=n62p45lthsqb");


 //       options.addArguments("-proxy-server=brd.superproxy.io:33335");
        // 创建Chrome浏览器的实例
        WebDriver driver = new ChromeDriver(options);


        // 打开网页
        driver.get("https://wbiprod.storedvalue.com/wbir/clients/arcteryx?lng=en");
        
        // 等待页面加载完成
        WebDriverWait wait = new WebDriverWait(driver, 60); // 最多等待60秒
        
        try {
            // 等待直到可以找到cardNo元素
            wait.until(ExpectedConditions.presenceOfElementLocated(By.id("cardNo")));
            
            // 获取动态加载后的完整页面HTML
            String dynamicPageSource = (String) ((JavascriptExecutor) driver).executeScript("return document.documentElement.outerHTML;");
            System.out.println("动态加载后的页面HTML:");
            System.out.println(dynamicPageSource);
            
            // 选择ID为cardNo的输入框并输入内容122
            WebElement cardNoInput = driver.findElement(By.id("cardNo"));
            cardNoInput.sendKeys("6006496947757759315");

            // 选择ID为cardNo的输入框并输入内容122
            WebElement cardPinInput = driver.findElement(By.id("pin"));
            cardPinInput.sendKeys("9583");
            System.out.println("成功找到输入框并输入内容");

            // 根据类选择器找到按钮并点击
            WebElement button = driver.findElement(By.className("arcteryxButton"));
            button.click();
            System.out.println("成功点击按钮");
            
            // 等待并读取类选择器card-bal-val的内容
            wait.until(ExpectedConditions.presenceOfElementLocated(By.className("card-bal-val")));
            WebElement balanceElement = driver.findElement(By.className("card-bal-val"));
            String balanceText = balanceElement.getText();
            System.out.println("获取到的余额信息: " + balanceText);
        } catch (TimeoutException e) {
            System.out.println("超时：无法找到ID为'cardNo'的元素或页面加载超时");
            
            // 即使找不到元素，也尝试获取当前页面源码
            String currentPageSource = driver.getPageSource();
            System.out.println("当前页面HTML源码:");
            System.out.println(currentPageSource);
        } catch (NoSuchElementException e) {
            System.out.println("无法找到指定的按钮元素或card-bal-val元素");
        }

        // 关闭浏览器
    //    driver.quit();
    }

    /**
     * 创建带认证的代理扩展
     */
    private static String createProxyAuthExtension(String proxyHost, int proxyPort,
                                                   String proxyUser, String proxyPassword) throws IOException {
        // 创建临时ZIP文件
        String zipPath = System.getProperty("java.io.tmpdir") + "proxy_auth_extension.zip";

        try (FileOutputStream fos = new FileOutputStream(zipPath);
             ZipOutputStream zos = new ZipOutputStream(fos)) {

            // manifest.json内容
            String manifestJson = "{\n" +
                    "  \"version\": \"1.0.0\",\n" +
                    "  \"manifest_version\": 2,\n" +
                    "  \"name\": \"Chrome Proxy\",\n" +
                    "  \"permissions\": [\n" +
                    "    \"proxy\",\n" +
                    "    \"tabs\",\n" +
                    "    \"unlimitedStorage\",\n" +
                    "    \"storage\",\n" +
                    "    \"<all_urls>\",\n" +
                    "    \"webRequest\",\n" +
                    "    \"webRequestBlocking\"\n" +
                    "  ],\n" +
                    "  \"background\": {\n" +
                    "    \"scripts\": [\"background.js\"]\n" +
                    "  },\n" +
                    "  \"minimum_chrome_version\": \"22.0.0\"\n" +
                    "}";

            // background.js内容
            String backgroundJs = "var config = {\n" +
                    "  mode: \"fixed_servers\",\n" +
                    "  rules: {\n" +
                    "    singleProxy: {\n" +
                    "      scheme: \"http\",\n" +
                    "      host: \"" + proxyHost + "\",\n" +
                    "      port: " + proxyPort + "\n" +
                    "    },\n" +
                    "    bypassList: [\"localhost\"]\n" +
                    "  }\n" +
                    "};\n" +
                    "chrome.proxy.settings.set({value: config, scope: \"regular\"}, function() {});\n" +
                    "function callbackFn(details) {\n" +
                    "  return {\n" +
                    "    authCredentials: {\n" +
                    "      username: \"" + proxyUser + "\",\n" +
                    "      password: \"" + proxyPassword + "\"\n" +
                    "    }\n" +
                    "  };\n" +
                    "}\n" +
                    "chrome.webRequest.onAuthRequired.addListener(\n" +
                    "  callbackFn,\n" +
                    "  { urls: [\"<all_urls>\"] },\n" +
                    "  ['blocking']\n" +
                    ");";

            // 添加manifest.json到ZIP
            ZipEntry manifestEntry = new ZipEntry("manifest.json");
            zos.putNextEntry(manifestEntry);
            zos.write(manifestJson.getBytes());
            zos.closeEntry();

            // 添加background.js到ZIP
            ZipEntry backgroundEntry = new ZipEntry("background.js");
            zos.putNextEntry(backgroundEntry);
            zos.write(backgroundJs.getBytes());
            zos.closeEntry();
        }

        return zipPath;
    }
}